package com.example.java.Service.Impl;

import cn.xfyun.api.FaceCompareClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.example.java.Entity.User;
import com.example.java.Mapper.UserMapper;
import com.example.java.Service.FaceService;
import com.example.java.base.ImageUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.IOUtils;



import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


@Service
public class FaceServiceImpl implements FaceService {

    @Autowired
    private UserMapper userMapper;

    private String appId = "acc505f1";

    private String apiKey = "3895520c0ffb6b0d4c3a6d20ba59b35b";

    private String apiSecret = "YjQ5NjFmMzFiYzRiZjc2MjFlOGNmNTAw";

    private FaceCompareClient init(){
        return new FaceCompareClient
                .Builder(appId, apiKey, apiSecret)
                .build();
    }


    @Override
    @SneakyThrows(Exception.class)
    public Boolean faceContrast(String username, String base64) {
        InputStream inputStream = new FileInputStream(new File("C:\\Users\\zl133\\Desktop\\a.jpg"));
        byte[] imageByteArray = IOUtils.readFully(inputStream, -1, true);
        String imageBase64 = Base64.getEncoder().encodeToString(imageByteArray);
        System.out.println(init().faceCompare(imageBase64, "jpg", imageBase64, "jpg"));
        return null;
    }

    @SneakyThrows(Exception.class)
    public boolean contrastz(String avatar,Integer id)  {
        String base64Str = ImageUtil.convertImageToBase64Str(avatar);
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, id));
        String localPath = user.getAvatar();
        InputStream inputStream = new FileInputStream(new File(localPath));
        byte[] imageByteArray = IOUtils.readFully(inputStream, -1, true);
        String remoteBase = Base64.getEncoder().encodeToString(imageByteArray);
        String s = init().faceCompare(avatar, "jpg", remoteBase, "jpg");
        byte[] decodedBytes = Base64.getDecoder().decode(s);
        String decodedStr = new String(decodedBytes, StandardCharsets.UTF_8);
//        System.out.println(decodedStr); // 输出： Hello world
        if (Double.parseDouble(decodedStr) >= 0.95){
            return true;
        }else {
            return false;
        }
    }
}
